package cn.gson.springboot.model.service.productservice;

import cn.gson.springboot.model.dao.productDao.*;
import cn.gson.springboot.model.dao.saledao.ZproductsideDao;
import cn.gson.springboot.model.mapper.productmapper.ProductInfoMapper;
import cn.gson.springboot.model.pjos.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
public class ProductInfoService {
    private  Zproductside zproductsideInfo;//持久化产品对象

    private Integer zproductMainIdInfo;//持久化产品对象id


    @Autowired
    ProductInfoMapper productInfoMapper;
    @Autowired
    ZspecificationsDao zspecificationsDao;
    @Autowired
    ZsproductDao zsproductDao;
    @Autowired
    ZproductcategoryDao zproductcategoryDao;

    @Autowired
    zproductmiddleEntityDao middleDao;
    @Autowired
    ZproductbrandDao zproductbrandDao;

    @Autowired
    ZsproudctMainDao zsproudctMainDao;//产品主表

    @Autowired
    ZproductsideDao zproductsideDao;//副标
    @Autowired
    ZsidesmodelmiddleDao zsidesmodelmiddleDao;//中间表

    @Autowired
    ZproductImgpathDao imgpathDao;

    public Zproductside productMain(Integer psId){
        Zproductside zproductside = productInfoMapper.productMain(psId);
        return zproductside;

    }



    public Zproductcategory getInfo(Integer id){
        Zproductcategory zproductcategory = zproductcategoryDao.findById(id).get();
        return zproductcategory;
    }

    public Zproductbrand getBrandInfo(Integer id){
        Zproductbrand zproductbrand = zproductbrandDao.findById(id).get();
        return zproductbrand;
    }

    public List<Products> productsList(Integer productTpye,String productName){
        List<Products> products = productInfoMapper.productInfo(productTpye,productName);
        return  products;
    }

    public List<Productbrand>ProductbrandList(){
        List<Productbrand> productbrands = productInfoMapper.BrandList();
        return  productbrands;
    }


    public List<Zproduct> zproductList(){
        List<Zproduct> zproducts = productInfoMapper.newProductInfo();
        return zproducts;
    }



    public List<Zspecifications> zspecificationsList(Integer id){
        List<Zspecifications> zspecifications = productInfoMapper.zspecificationsList(id);
        return zspecifications;
    }


    /**
     * 新增规格值
     */
    public void addZsp(Zspecificationsvalue zspecificationsvalue){
        zsproductDao.save(zspecificationsvalue);
    }


    public Zspecifications ZspeFindById(Integer id){
        Zspecifications zspecifications = zspecificationsDao.findById(id).get();
        return zspecifications;
    }


    /**
     * 新增产品规格
     * @param name
     */
    public void addZspecificationsinfo(Integer id, String name,String zspeValue){
        Zspecifications zspecifications = new Zspecifications();
        zspecifications.setOnsId(0);
        zspecifications.setOnsName(name);
        Zspecifications save = zspecificationsDao.save(zspecifications);

     /*   Zproductmodelmiddle zproductmodelmiddle = new Zproductmodelmiddle();
        Zproductcategory zproductcategory = zproductcategoryDao.findById(id).get();
        zproductmodelmiddle.setMiddle(zproductcategory);
        zproductmodelmiddle.setZspecificationsByOnsId(save);
*/

        /*ZproductmodelmiddleEntityPK middle = new ZproductmodelmiddleEntityPK();*/
        ZproductmodelmiddleEntity middle= new ZproductmodelmiddleEntity();
        middle.setOnsId(save.getOnsId());
        middle.setProductId(id);
        middleDao.save(middle);

        //对应的规格值
        Zspecificationsvalue addzspecificationsvalue = addzspecificationsvalue(save, zspeValue);



    }

    /**
     * 新增产品规格下的规格值
     */
    public Zspecificationsvalue addzspecificationsvalue(Zspecifications zspecifications,String name){
        Zspecificationsvalue zsp = new Zspecificationsvalue();
        zsp.setSpecId(0);
        zsp.setSpecVlaue(name);
        zsp.setZspecificationsByOnsId(zspecifications);
        Zspecificationsvalue save = zsproductDao.save(zsp);
        return save;
    }

    public Timestamp utilDateToTimestamp(){
        java.util.Date utilDate = new java.util.Date();//util.Date
        long time = utilDate.getTime();
        return new Timestamp(time);
    }


    /**
     * 产品保存
     * @param productInfo
     * @param info
     */
    public Integer productModelSave(String productInfo,String info){
        Object o = JSONObject.toJSON(info);
        JSONObject jsonx = JSON.parseObject(info);
        Zproduct zproduct = new Zproduct();

        Integer pcId = jsonx.getInteger("pcId");
        Zproductcategory info1 =getInfo(pcId);//类型
        Integer pdId = jsonx.getInteger("pdId");
        Zproductbrand brandInfo =getBrandInfo(pdId);//品牌
        String name = jsonx.getString("name");
        String model = jsonx.getString("model");
        BigDecimal factoryPrice = jsonx.getBigDecimal("factoryPrice");
        BigDecimal price = jsonx.getBigDecimal("price");
        String imgpath = jsonx.getString("imgpath");
        String unit = jsonx.getString("unit");
        Integer number = jsonx.getInteger("number");

        //产品主表(缺主主图片)
        zproduct.setProductName(name);
        zproduct.setPrModel(model);
        zproduct.setZproductbrandByPdId(brandInfo);
        zproduct.setZproductcategoryByPcId(info1);
        String s = zproduct.toString();
        System.out.println("产品主表信息"+s);
        Zproduct save = zsproudctMainDao.save(zproduct);


        //产品副标
        Zproductside zproductside = new Zproductside();
        java.util.Date utilDate = new java.util.Date();//util.Date
        Timestamp timestamp = utilDateToTimestamp();
        zproductside.setPsDate(timestamp);
        zproductside.setPsPrice(price);
        zproductside.setPsNumber(number);
        zproductside.setPsState(1);
        zproductside.setPsUnit(unit);
        zproductside.setPsFactoryPrice(factoryPrice);
        zproductside.setZproductByProductId(save);

        Zproductside save1 = zproductsideDao.save(zproductside);
        System.err.println("规格信息"+productInfo);

        String skh ="(\\d+)";
        Pattern pattern = Pattern.compile(skh);
        Matcher matcher = pattern.matcher(productInfo);
        String tpl=null;
        while (matcher.find()){
            String group = matcher.group();
            ZsidesmodelmiddleEntity middle= new ZsidesmodelmiddleEntity();
            middle.setSpecId(Integer.parseInt(group));//规格值
            middle.setPsId(save1.getPsId());//副标id
            zsidesmodelmiddleDao.save(middle);
        }
        zproductMainIdInfo=zproductside.getZproductByProductId().getProductId();
        zproductsideInfo=save1;

        return save1.getPsId();

    }



   /* public String  imgPathSave(MultipartFile[] uploadFiles){
        String [] imgPath= new String[uploadFiles.length];

       *//* Zproductside zproductside = zproductsideDao.findById(returnid).get();
        System.out.println("副标id"+zproductside.getPsId());
        System.out.println("主表id"+zproductside.getZproductByProductId().getProductId());*//*
        if(zproductsideInfo!=null){
            return "对象不存在";
        }

        //1，对文件数组做判空操作
        if (uploadFiles == null || uploadFiles.length < 1) {

            return "未选择文件!";
        }
        //2，定义文件的存储路径,
        String uri = "E:/upload";
        File dir = new File(uri);
        if (!dir.isDirectory()) {//文件目录不存在，就创建一个
            dir.mkdirs();
        }

        String filePathS = "";
        //3，遍历文件数组，一个个上传
        for (int i = 0; i < uploadFiles.length; i++) {
            System.out.println("小六在"+i);
            MultipartFile file = uploadFiles[i];
            String fileName = file.getOriginalFilename();
            String ext = FilenameUtils.getExtension(fileName);
            //生成一个新的名字
            String newName = UUID.randomUUID().toString();
            String filePath = newName + "." + ext;
            imgPath[i]="http://localhost:8088/"+"upload/"+filePath;
            File f = new File(uri,filePath);
            try {
                //文件转移
                file.transferTo(f);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        Zproductimgs zproductimgs = new Zproductimgs();
        zproductimgs.setImgsId(0);
        zproductimgs.setZproductsideByPsId(zproductsideInfo);
        zproductimgs.setImgsaSrc(imgPath[0]);
        zproductimgs.setImgsbSrc(imgPath[1]);
        zproductimgs.setImgscSrc(imgPath[2]);
        imgpathDao.save(zproductimgs);

        return "";

    }*/


    public Integer imgPath(Zproductimgs zproductimgs){
        Zproductimgs save = imgpathDao.save(zproductimgs);
        return save.getImgsId();
    }

    public void imgPathSave(String[] array,Integer returnId,Integer imgPathId){
        Zproductside zproductside = zproductsideDao.findById(returnId).get();

        System.out.println("副标id"+zproductside.getPsId());
        System.out.println("主表id"+zproductside.getZproductByProductId().getProductId());


        Zproduct zproduct = zsproudctMainDao.findById(zproductside.getZproductByProductId().getProductId()).get();
        zproduct.setPrImgpath(array[0]);
        zsproudctMainDao.save(zproduct);

        Zproductimgs zproductimgs = imgpathDao.findById(imgPathId).get();
        zproductimgs.setZproductsideByPsId(zproductside);
        imgpathDao.save(zproductimgs);
    }

}
